from llama_index.readers.dashscope.base import DashScopeParse
from llama_index.readers.dashscope.utils import ResultType
from llama_index.indices.managed.dashscope import DashScopeCloudIndex
from llama_index.llms.dashscope import DashScope, DashScopeGenerationModels
import json
from dependencies import DASHSCOPE_API_KEY


async def parse_document(file_path):
    parse = DashScopeParse(result_type=ResultType.DASHSCOPE_DOCMIND)
    documents = await parse.aload_data(file_path=file_path)
    return documents


def process_parsed_result(documents):
    # 获取第一个 Document 对象的 text 属性
    document = documents[0]
    if not hasattr(document, 'text'):
        raise ValueError("Document 对象缺少 text 属性。")
    text_content = document.text
    text_content = json.loads(text_content)
    parsed_result = json.loads(text_content)
    # 提取文档信息
    doc_info = {
        "docType": parsed_result["docInfo"].get("docType", "未知类型"),
        "paragraphCount": parsed_result["docInfo"].get("paragraphCount", 0),
        "pageCountEstimate": parsed_result["docInfo"].get("pageCountEstimate", 0),
        "imageCount": parsed_result["docInfo"].get("imageCount", 0),
        "tableCount": parsed_result["docInfo"].get("tableCount", 0)
    }
    # 构建层级结构 HTML
    layouts = parsed_result["layouts"]
    hierarchy_html = build_hierarchy(layouts)
    # 将处理后的结果组合起来
    processed_result = {
        "docInfo": doc_info,
        "hierarchyHTML": hierarchy_html
    }
    return processed_result


def build_hierarchy(layouts, level=0):
    def process_layout(layout, level):
        indent = "  " * level
        html = ""

        if "subType" in layout and layout["subType"] in ["doc_title", "para_title"]:
            # 使用加粗表示标题
            html += f"{indent}<li><strong>{layout['text']}</strong>\n"
        else:
            html += f"{indent}<li>{layout['text']}\n"

        # 递归构建子层级
        if "blocks" in layout and layout["blocks"]:
            html += f"{indent}  <ul>\n"
            for block in layout["blocks"]:
                if "text" in block:
                    # 避免重复处理父层级的 text 字段
                    if block["text"] != layout["text"]:
                        html += process_layout(block, level + 1)
            html += f"{indent}  </ul>\n"

        html += f"{indent}</li>\n"
        return html

    html = "<ul>\n"
    for layout in layouts:
        html += process_layout(layout, level + 1)
    html += "</ul>\n"
    return html




